package com.example.template.controller;

import com.example.template.common.api.ApiCodeConstant;
import com.example.template.common.api.ApiResult;
import com.example.template.common.constant.TokenConstant;
import com.example.template.common.exception.GlobalException;
import com.example.template.dto.UserDTO;
import com.example.template.entity.User;
import com.example.template.query.UserQuery;
import com.example.template.service.PermissionService;
import com.example.template.service.UserService;
import com.example.template.utils.JsonUtil;
import com.example.template.utils.JwtUtil;
import com.example.template.utils.RedisUtil;
import com.example.template.utils.TokenUtil;
import com.example.template.vo.UserEditModel;
import com.example.template.vo.UserModel;
import com.example.template.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @className: UserController
 * @description: TODO 类描述
 * @author: Kuangkeli
 * @date: 2024/01/18 22:31
 **/
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PermissionService permissionService;


    @PostMapping("/login")
    public ApiResult login(@RequestBody UserQuery userQuery, @RequestHeader(value = "client_type", required = false, defaultValue = "web") String clientType) {
        System.out.println("username = [" + userQuery.getUsername() + "], password = [" +
                userQuery.getPassword() + "]");
        UserDTO userDTO = userService.login(userQuery.getUsername(), userQuery.getPassword());
        if (userDTO != null) {
            Map<String, Object> payload = new HashMap<>();
            //生成用户对应的token 作为key加入到redis中用户信息作为value 并加入jwt载荷 后续可以从redis中
            //解析出token 从而在redis中获取用户的信息
            String token = tokenUtil.generateTokenValue(clientType,userDTO.getUserId(),userQuery.getPassword());
            payload.put("userId",userDTO.getUserId().toString());
            payload.put("username",userDTO.getUsername());
            payload.put("client_type",clientType);

            //查询用户的权限信息 添加至redis
            List<String> perms = permissionService.getPermsListByUserId(userDTO.getUserId());
            String permStr = JsonUtil.obj2String(perms);
            redisUtil.set("perms:"+userDTO.getUserId(),permStr);

            redisUtil.hmset(token,payload, TokenConstant.TOKEN_EXPIRE_TIME);
            payload.put("token",token);
            String jwt = jwtUtil.getToken(payload);
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userDTO, userVO);
            ApiResult ajax = ApiResult.success("登录成功", userVO);
            //将jwt返回前端 由前端存储 后续请求携带
            ajax.put("token",jwt);
            return ajax;
        }
        throw new GlobalException(ApiCodeConstant.RESULT_LOGIN_FAIL, "用户名或密码错误");
    }



//    /**
//     * 登出
//     *
//     * @return
//     */
//    @PostMapping("/logOut/{token}")
//    public ApiResult logOut(@PathVariable("token") String token) {
//
//    }
//
//    /**
//     * 注销
//     *
//     * @return
//     */
//    @PostMapping("/logOff/{token}")
//    public ApiResult logOff(@PathVariable("token") String token)
//    }


    @RequestMapping("/api/user/add")
    public boolean add(@RequestBody @Validated UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.insert(user);
        return true;
    }


    @GetMapping("/api/user/get")
    public ApiResult get(@RequestParam("userId") Long userId) {
        User user = userService.selectByPrimaryKey(userId);
        UserEditModel userEditModel = new UserEditModel();
        BeanUtils.copyProperties(user,userEditModel);
        userEditModel.setRoles(userService.getRolesByUserID(userId));
        return ApiResult.success(userEditModel);
    }

    @GetMapping("/api/user/getAllUser")
    public ApiResult getAllUser() {
        List<User> userList = userService.getAllUser();
        List<UserModel> userModelList = new ArrayList<>();
        if (!userList.isEmpty()){
            for (User u:userList) {
                UserModel um = new UserModel();
                BeanUtils.copyProperties(u,um);
                userModelList.add(um);
            }
        }
        return ApiResult.success(userModelList);
    }

    @PostMapping("/api/user/update")
    public ApiResult updateUser(@RequestBody UserEditModel userEditModel){
        userService.updateUser(userEditModel);
        return ApiResult.success("更新成功");
    }

}

